package com.lgd.warehousemanagement.Activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easy.view.dialog.EasyDialog;
import com.easy.view.utils.EasyUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.warehousemanagement.Adapter.MyAdapter;
import com.lgd.warehousemanagement.Bean.FactoryDeviceManagement;
import com.lgd.warehousemanagement.Bean.ProjectManagement;
import com.lgd.warehousemanagement.Bean.ProjectSpinner;
import com.lgd.warehousemanagement.Bean.ProjectType;
import com.lgd.warehousemanagement.Bean.SysUser;
import com.lgd.warehousemanagement.Bean.WorkHourCache;
import com.lgd.warehousemanagement.Bean.WorkHourStatistics;
import com.lgd.warehousemanagement.R;
import com.lgd.warehousemanagement.Utils.CacheDataManager;
import com.lgd.warehousemanagement.Utils.LogUtils;
import com.lgd.warehousemanagement.Utils.ScreenUtils;
import com.lgd.warehousemanagement.Utils.TimeUtils;
import com.lgd.warehousemanagement.Utils.ToastUtils;
import com.lgd.warehousemanagement.databinding.ActivityMainBinding;
import com.lgd.warehousemanagement.databinding.AfterWorkPopBinding;
import com.lgd.warehousemanagement.databinding.MenuPopBinding;
import com.lgd.warehousemanagement.databinding.SwipeCardPopBinding;
import com.lgd.warehousemanagement.httpService.API;
import com.lgd.warehousemanagement.httpService.httpPort.IResponse;
import com.lgd.warehousemanagement.httpService.httpPort.IStringResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android_serialport_api.SerialPortUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    ActivityMainBinding mainBinding;
    private static final String TAG = "--刷卡界面--";
    private TextToSpeech textToSpeech = null;   //创建自带语音对象
    private String scanResult, ANDROID_ID;
    private Long userID ,deptID;
    private final List<ProjectSpinner> projectnameList = new ArrayList<>();  // 项目 列表
    SerialPortUtils serialPortUtils;   // 串口对象
    private static String twoEnterDoor;    //  第二道进门设备 ID
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());
        MainInit();
        MainListener();
        initTTS();
//        transparentNavBar(this);   /// 底部导航栏透明
    }

    // MainActivity 初始化
    @SuppressLint("HardwareIds")
    public void MainInit(){
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().register(MainActivity.this);    // 注册事件
                serialPortUtils = new SerialPortUtils();
                serialPortUtils.openSerialPort(4);        // 打开串口  /dev/ttyS0
                ANDROID_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                Log.d(TAG, " 安卓设备信息 ANDROID_ID: " + ANDROID_ID);
                closeInput(mainBinding.etCardNumber);
                clockRule();
            }
        });
//        mainBinding.multiStateView.setViewState(MultiStateView.ViewState.CONTENT);
    }
    // 刷卡 事件 监听
    public void clockRule(){
        mainBinding.etCardNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE ||
                        event.getAction() == KeyEvent.ACTION_DOWN &&
                                event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    scanResult = mainBinding.etCardNumber.getText().toString();
                    if (scanResult.length() > 0 ){
                        if (scanResult.length() != 10){
                            mainBinding.etCardNumber.setText("");
                            ToastUtils.warnShowLong(MainActivity.this,"卡片读取有误！请重新刷卡！");
                        }else{
                            mainBinding.etCardNumber.setText(scanResult);
                            setSeleceStaffInfo(scanResult,null);
                        }
                    }
                    return true;
                }
                return false;
            }
        });
    }
    // 获取员工数据
    public void setSeleceStaffInfo(String icCard,String name){
        SysUser sysUser = new SysUser();
        if (icCard == null && name == null){
            seleceStaffInfo(sysUser);
            return;
        }
        if (icCard == null){
            sysUser.setNickName(name);
        }
        if (name == null){
            sysUser.setIcCard(icCard);
        }
        seleceStaffInfo(sysUser);
    }

    // MainActivity 设置监听
    public void MainListener(){
        mainBinding.tvMenu.setOnClickListener(this);
        mainBinding.layoutDoor.setOnClickListener(this);
//        mainBinding.layoutDoor.setBackgroundResource(R.drawable.round_background);
        mainBinding.ivAbnormalOrder.setOnClickListener(this);
        mainBinding.layoutCart.setOnClickListener(this);
        mainBinding.layoutPersonnel.setOnClickListener(this);
        mainBinding.ivWarn.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_menu:
                showMenuPop();
                break;
            case R.id.layout_personnel:
                System.out.println("点击   -----人员进入.........");
                if (is_enter_out){
                    serialPortUtils.sendSerialPort("5501000000aa");
                }else {
                    ToastUtils.warnShowLong(MainActivity.this,"请刷卡上报后，再点击开门！");
                }
                break;
            case R.id.layout_cart:
                System.out.println("点击推车进入.........");
                if (is_enter_out){     // true
                    serialPortUtils.sendSerialPort("5502000000aa");
                }else {
                    ToastUtils.warnShowLong(MainActivity.this,"请刷卡上报后，再点击开门！");
                }
                break;
            case R.id.layout_door:
                if (is_enter_out){     // true
                    serialPortUtils.sendSerialPort("5503000000aa");
                }else {
                    ToastUtils.warnShowLong(MainActivity.this,"请刷卡上报后，再点击开门！");
                }
                break;
            case R.id.iv_warn:
                serialPortUtils.sendSerialPort("5504000000aa");
                break;
            case R.id.iv_abnormal_order:  // 异常订单
                startActivity(new Intent(MainActivity.this,AbnormalOrderActivity.class));
                break;

            default:
                break;
        }
    }

    //接收主板回传信息
    @SuppressLint("ResourceType")
//    @Subscribe(threadMode = ThreadMode.MAIN)
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventMainThread(String msg) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("------接收到串口数据",msg);
                switch (msg) {
                    case "550100010000AA":
                        ToastUtils.successShowLong(getApplicationContext(),"开门成功!");
                        startAuto("开门成功！");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                is_enter_out = false;
                            }
                        }, 15 * 1000);

                        break;
                    case "550200010000AA":
                        ToastUtils.successShowLong(getApplicationContext(),"推车开门成功!");
                        startAuto("推车进入成功！");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                is_enter_out = false;
                            }
                        }, 15 * 1000);
                        break;
                    case "550300020000AA":
                        ToastUtils.successShowLong(getApplicationContext(),"叉车开门成功!");
                        startAuto("叉车进入成功！");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                is_enter_out = false;
                            }
                        }, 15 * 1000);
                        break;
                    case "550400010000AA":
                        ToastUtils.successShowLong(getApplicationContext(),"大门关闭");
                        startAuto("大门关闭");
                        break;
                    case "550100013100AA":
                        startAuto("进门领料，请先刷卡！");
                        break;
                    case "550100013200AA":
                        startAuto("领料完成后，请先上报日志！");
                        break;
                    default:
                        is_enter_out = true;
                        closeDoorStatus();
                        break;
                }
            }
        });
    }

    //  获取 员工 信息
    public void seleceStaffInfo(SysUser sysUser){
        API.seleceStaffInfo(sysUser, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<SysUser> sysUserList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<SysUser>>(){}.getType());
                        LogUtils.d(TAG,"---员工信息-----"+sysUserList);
                        switch (sysUserList.size()){
                            case 0:
                                ToastUtils.warnShowLong(getApplicationContext(),"此卡为空卡，请联系管理员添加");
                                mainBinding.etCardNumber.setText("");
                                startAuto("此卡为空卡，请联系管理员添加");
                                break;
                            case 1:
                                userID = sysUserList.get(0).getUserId();
                                deptID = sysUserList.get(0).getDeptId();
                                startAuto("刷卡成功"+sysUserList.get(0).getNickName());

                                // 用户 状态
                                WorkHourCache workHourCache = new WorkHourCache();
                                workHourCache.setUserid(userID);
                                workHourCache.setAndroidID(ANDROID_ID);
                                selectCacheStatus(workHourCache, sysUserList);    // 状态查询

                                break;
                            default:
                                break;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.warnShowLong(getApplicationContext(),"数据请求异常！！！");
                        mainBinding.etCardNumber.setText("");
                    }
                });
            }
        });
    }
    //  缓存表 与 工时表 查询
    public void selectCacheStatus(WorkHourCache workHourCache, List<SysUser> sysUserList){
        API.selectCacheStatus(workHourCache, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        Map<String,String> map = new HashMap<>();
                        JSONObject strJson = JSONObject.parseObject(result);
                        map= gson.fromJson(strJson.toString(), map.getClass());
                        //  领料缓存卡数据
                        List<WorkHourCache> workHourCacheList =
                                JSON.parseArray(map.get("workHourCacheList"),WorkHourCache.class);
                        //  工时表数据
                        List<WorkHourStatistics> workHourStatisticsList =
                                JSON.parseArray(map.get("workHourStatisticsList"),WorkHourStatistics.class);
                        //  设备信息
                        List<FactoryDeviceManagement> deviceInfos =
                                    JSON.parseArray(map.get("deviceList"), FactoryDeviceManagement.class);
                        //  缓存过期 工单
                        List<WorkHourCache> oldCacheList =
                                JSON.parseArray(map.get("oldCacheList"),WorkHourCache.class);

                       Log.d(TAG, "----领料缓存-----"+workHourCacheList+"****今日工单数据****"+workHourStatisticsList
                                            + "****设备信息****"+deviceInfos+"****过期缓存工单----"+oldCacheList);
                       if (deviceInfos.isEmpty()){
                            ToastUtils.warnShowLong(getApplicationContext(),"设备未配置,请联系管理员配置设备");
                            return;
                       }

                       String deviceName = deviceInfos.get(0).getDevicename().trim();   // 设备名称
                       String deviceRemark = deviceInfos.get(0).getRemark().trim();     // 设备备注信息
                       String deptName = sysUserList.get(0).getDept().getDeptName();   // 部门名称
                       if (deviceName.equals("第二道进门设备") || deviceName.equals("第二道出门设备")){
                           if (deptName.equals("仓储部")){
                               Log.d(TAG, "第二道门------仓管人员 进入");
//                               serialPortUtils.sendSerialPort("5503000000aa");
                               is_enter_out = true;
                               mainBinding.etCardNumber.setText("");
                           }else {
                               ToastUtils.warnShowLong(getApplicationContext(),"非仓储人员，无法进入");
                               startAuto("非仓储人员，无法进入");
                               mainBinding.etCardNumber.setText("");
                           }
                           return;
                       }
                        switch (deviceRemark) {
                            case "进门":
                                Log.d(TAG, "run: ----进门人员信息----"+sysUserList);
                                if (workHourCacheList.isEmpty()){
                                    if (deptName.equals("仓储部")){
                                        Log.d(TAG, "run: 仓储部人员..........");
                                        showReportTipDialog(sysUserList); // 上报 仓储 数据
                                    }else {
                                        showSwipeCardPop(sysUserList,workHourStatisticsList,oldCacheList);   //  显示 刷卡 弹窗
                                    }
                                }else {
                                    mainBinding.etCardNumber.setText("");
                                    if (deptName.equals("仓储部")){
                                        try {
                                            setWorkCacheUpdate(workHourCacheList);
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                    }else {
                                        ToastUtils.warnShowLong(getApplicationContext(),"今日上一工单未上报日报，请先上报日报！");
                                        showAfterWorkPop(sysUserList,workHourCacheList,false);
                                    }
                                }
                                break;
                            case "出门":
                                // TODO: 2024/12/18 主要进行下班上报处理，对于进门未打卡出门没工单  需进行补卡处理 自行选择 领料开始以及结束
                                if (workHourCacheList.isEmpty()){
                                    ToastUtils.warnShowLong(getApplicationContext(),"进门前未打卡，找不到工单！");
                                    mainBinding.etCardNumber.setText("");
                                }else {
                                    mainBinding.etCardNumber.setText("");
                                    if (deptName.equals("仓储部")){
                                        Log.d(TAG, "仓储出门......");
                                        try {
                                            setWorkCacheUpdate(workHourCacheList);
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                    }else {
                                        showAfterWorkPop(sysUserList,workHourCacheList,false);  // 显示 上报 弹窗
                                    }
                                }
                                 break;
                            default:
                                ToastUtils.warnShowLong(getApplicationContext(),"该设备不属于门禁设备");
                                break;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.warnShowLong(getApplicationContext(),"数据请求异常！！！");
                        mainBinding.etCardNumber.setText(null);
                    }
                });
            }
        });
    }
    //  刷卡 弹窗
    PopupWindow swipe_card_pop;
    SwipeCardPopBinding swipeCardPopBinding;
    public void showSwipeCardPop(List<SysUser> sysUserList, List<WorkHourStatistics> w, List<WorkHourCache> oldCacheList){
        workhourID = null;
        swipeCardPopBinding = SwipeCardPopBinding.inflate(getLayoutInflater());
        View swipeCard_view = swipeCardPopBinding.getRoot();
        int width = ScreenUtils.getWidth(MainActivity.this);
        swipe_card_pop = new PopupWindow
                    (swipeCard_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        swipe_card_pop.setTouchable(true);
        swipe_card_pop.setFocusable(true);   // 弹窗焦点
        swipe_card_pop.setOutsideTouchable(true);
        swipe_card_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        setSwipeCardPopListener(sysUserList,oldCacheList);
        if (!w.isEmpty()){
            workhourID = w.get(0).getWorkhourid();
        }
        projectType();
        Log.d(TAG, "showSwipeCardPop: --00000--"+sysUserList.get(0).getNickName()+"(工号："+sysUserList.get(0).getIcCard()+")");
        swipeCardPopBinding.tvSwipeName.setText(sysUserList.get(0).getNickName()+"(工号："+sysUserList.get(0).getIcCard()+")");
        swipeCardPopBinding.tvSwipeGroup.setText(sysUserList.get(0).getDept().getDeptName());
        swipeCardPopBinding.tvSwipeTime.setText(TimeUtils.getCurrentDateTime());
        swipe_card_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }
    // 刷卡 弹窗 监听
    public void setSwipeCardPopListener(List<SysUser> sysUserList, List<WorkHourCache> oldCacheList){
        setAlpha(0.2f);
        swipeCardPopBinding.btSwipeSubmit.setOnClickListener(new View.OnClickListener() {   //  提交
            @Override
            public void onClick(View v) {
                if (long_projectId == null){
                    ToastUtils.warnShowLong(getApplicationContext(),"项目不为空！");
                    return;
                }
                WorkHourCache workHourCache = new WorkHourCache();
                workHourCache.setWorkhourid(workhourID);
                workHourCache.setProducedate(TimeUtils.getCurrentDate());
                workHourCache.setProjectid(long_projectId);
                workHourCache.setDeptid(sysUserList.get(0).getDept().getDeptId());// 用户 的部门 id
                workHourCache.setUserid(userID);
                workHourCache.setStarttime(swipeCardPopBinding.tvSwipeTime.getText().toString());
                workHourCache.setClocktype("领料");
                addWorkHourCache(workHourCache); // 添加 领料
                swipeCardPopBinding.btSwipeSubmit.setEnabled(false);
            }
        });
        swipe_card_pop.setOnDismissListener(() -> {        //  监听 弹窗 关闭
            setAlpha(1f);
            mainBinding.etCardNumber.setText("");
            if (!oldCacheList.isEmpty() && is_enter_out){
                showDialog(sysUserList,oldCacheList);
            }
        });
        swipeCardPopBinding.ivSwipeClose.setOnClickListener(new View.OnClickListener() {   // 手动关闭弹窗
            @Override
            public void onClick(View v) {
                swipe_card_pop.dismiss();
            }
        });
        swipeCardPopBinding.ivRefresh.setOnClickListener(new View.OnClickListener() {     //  刷新
            @Override
            public void onClick(View v) {
                cleanProject();
                projectType();
            }
        });
    }
    // 下工 打卡弹窗
    PopupWindow after_work_pop;
    AfterWorkPopBinding afterWorkPopBinding;
    @SuppressLint("SetTextI18n")
    public void showAfterWorkPop(List<SysUser> sysUserList, List<WorkHourCache> workHourCacheList, Boolean is_expired_not){
        afterWorkPopBinding = AfterWorkPopBinding.inflate(getLayoutInflater());
        View after_work_view = afterWorkPopBinding.getRoot();
        int width = ScreenUtils.getWidth(MainActivity.this);
        after_work_pop = new PopupWindow
                (after_work_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        after_work_pop.setTouchable(true);
        after_work_pop.setFocusable(true);
        after_work_pop.setOutsideTouchable(true);
        after_work_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        after_work_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        setAfterWorkPopListener(workHourCacheList);
        afterWorkPopBinding.tvAfterName.setText(sysUserList.get(0).getNickName()+"(工号："+sysUserList.get(0).getIcCard()+")");
        afterWorkPopBinding.tvAfterGroup.setText(sysUserList.get(0).getDept().getDeptName());
        if (is_expired_not){      //   往期工单
            afterWorkPopBinding.tvAfterTime.setText("请选择时间");
            afterWorkPopBinding.tvAfterTime.setOnClickListener(v -> {
                TimeUtils.timeSelect(MainActivity.this, workHourCacheList.get(0).getStarttime(), new TimeUtils.TimePickerCallback() {
                    @Override
                    public void onTimePicked(Boolean b, String formattedDateTime) {
                        if (b){    // ture 代表 开始时间 > 结束时间
                            afterWorkPopBinding.tvAfterTime.setText("请选择时间");
                            afterWorkPopBinding.tvAfterDuration.setText(null);
                            ToastUtils.warnShowLong(getApplicationContext(),"选择的时间 < 开始时间，请重新选择！");
                        }else {
                            afterWorkPopBinding.tvAfterTime.setText(formattedDateTime);
                            setDuration(workHourCacheList);     //  设置 工时
                        }
                    }
                });
            });
        }else {
            afterWorkPopBinding.tvAfterTime.setText(TimeUtils.getCurrentDateTime());
            setDuration(workHourCacheList);
        }
        afterWorkPopBinding.tvStartTime.setText(workHourCacheList.get(0).getStarttime());
    }
    // 下工 打卡弹窗监听
    public void setAfterWorkPopListener(List<WorkHourCache> cache){
        setAlpha(0.2f);
        after_work_pop.setOnDismissListener(() -> {       //  监听 弹窗 关闭
            setAlpha(1f);
            mainBinding.etCardNumber.setText("");
        });
        afterWorkPopBinding.ivAfterClose.setOnClickListener(new View.OnClickListener() {   // 手动关闭弹窗
            @Override
            public void onClick(View v) {
                after_work_pop.dismiss();
            }
        });
        afterWorkPopBinding.btAfterSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_details = afterWorkPopBinding.etAfterDetails.getText().toString();
                String str_duration = afterWorkPopBinding.tvAfterDuration.getText().toString();
                String str_endTime = afterWorkPopBinding.tvAfterTime.getText().toString();
                if (str_endTime.equals("请选择时间")){
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择时间");
                    return;
                }
                if (str_duration.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"工时异常，请重新刷卡");
                    return;
                }
                if (str_details.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"请输入详情");
                    return;
                }
                // 提交数据  更新缓存表
                WorkHourCache workHourCache = new WorkHourCache();
                workHourCache.setProducedate(cache.get(0).getProducedate());
                workHourCache.setProjectid(cache.get(0).getProjectid());
                workHourCache.setDeptid(cache.get(0).getDeptid());
                workHourCache.setUserid(cache.get(0).getUserid());
                workHourCache.setStarttime(cache.get(0).getStarttime());
                workHourCache.setClocktype(cache.get(0).getClocktype());
                workHourCache.setEndtime(str_endTime);
                workHourCache.setWorkhourscacheid(cache.get(0).getWorkhourscacheid());
                workHourCache.setDuration(str_duration);
                workHourCache.setWorkhourid(cache.get(0).getWorkhourid());
                workHourCache.setIssueDetails(str_details);
                updateCache(workHourCache);    // 更新缓存表

                afterWorkPopBinding.btAfterSubmit.setEnabled(false);
            }
        });
    }
    // 设置 缓存表更新数据
    public void setWorkCacheUpdate(List<WorkHourCache> workHourCacheList) throws ParseException {
        TimeUtils.TimeInfo timeInfo = TimeUtils.getTime(workHourCacheList.get(0).getStarttime(),TimeUtils.getCurrentDateTime());
        Log.d(TAG, "打卡时间统计"+timeInfo.getTime()+ "结束的时间 "+ timeInfo.getTimeStr());
        if (timeInfo.getTime() < 0){
            ToastUtils.warnShowLong(getApplicationContext(),"打卡时间异常，请重新刷卡");
            return;
        }
        showGoOutTipDialog(timeInfo , workHourCacheList);
    }
    // 设置 上报 实体类数据
    public void setUpdateCache(List<WorkHourCache> cache,String str_details, String str_duration, String str_endTime){
        WorkHourCache workHourCache = new WorkHourCache();
        workHourCache.setProducedate(cache.get(0).getProducedate());
        workHourCache.setProjectid(cache.get(0).getProjectid());
        workHourCache.setDeptid(cache.get(0).getDeptid());
        workHourCache.setUserid(cache.get(0).getUserid());
        workHourCache.setStarttime(cache.get(0).getStarttime());
        workHourCache.setClocktype(cache.get(0).getClocktype());
        workHourCache.setEndtime(str_endTime);
        workHourCache.setWorkhourscacheid(cache.get(0).getWorkhourscacheid());
        workHourCache.setDuration(str_duration);
        workHourCache.setWorkhourid(cache.get(0).getWorkhourid());
        workHourCache.setIssueDetails(str_details);
        updateCache(workHourCache);
    }

    //  设置 工时 时间上报实体类
    public void setDuration( List<WorkHourCache> workHourCacheList){
        WorkHourStatistics w = new WorkHourStatistics();
        w.setStarttime(workHourCacheList.get(0).getStarttime());
        w.setEndtime(afterWorkPopBinding.tvAfterTime.getText().toString());
        w.setUserid(workHourCacheList.get(0).getUserid());
        calculateDuration(w);
    }
    //  根据开始 + 结束 + useid 查询工时
    String duration;
    public void calculateDuration(WorkHourStatistics w){
        duration = null;
        API.calculateDuration(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        duration = jsonObject.getString("msg");     // 工时
                        afterWorkPopBinding.tvAfterDuration.setText(duration);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        projectType_list.clear();
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"),
                                new TypeToken<List<ProjectType>>(){}.getType());
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
                        typeSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    //  类型 spinner 实例化
    ArrayAdapter<String> typeSpinner_adapter;
    public void typeSpinner(){
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,projectType_list);
        swipeCardPopBinding.spProjectType.setAdapter(typeSpinner_adapter);
        swipeCardPopBinding.spProjectType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str_spinner = projectType_list.get(position);
                cleanProject();
                if (str_spinner.equals("选择类型")) {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                }else {
                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    projectType.setSerialnumber(ANDROID_ID);
                    getStartProjectInfo(projectType);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    //  获取项目信息
    public void getStartProjectInfo(ProjectType projectType){
        API.getStartProjectInfo(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"),
                                new TypeToken<List<ProjectManagement>>(){}.getType());
                        projectnameList.clear();
                        String msg = j.getString("msg");
                        long l = Long.parseLong(j.getString("code"));
                        if (l == 200){
                            if (projectManagementList.size() > 0){
                                for (ProjectManagement p : projectManagementList) {
                                    projectnameList.add(new ProjectSpinner(p.getProjectname(),
                                            p.getProductacode(), p.getProjectid(),
                                            p.getDeptid() ,p.getElectricalBcode() ));
                                }
                            }else {
                                ToastUtils.warnShowLong(getApplicationContext(),"本设备下没有该类型的项目，请重新选择！");
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),msg);
                        }
                        setProject();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    String str_name, str_code;
    Long long_projectId, long_deptId , workhourID;
    MyAdapter adapter;
    List<String> codeList = new ArrayList<>();
    public void setProjectMsg(List<WorkHourStatistics> wList){
        cleanProjectSelectInfo();
        workhourID = null;
        str_name = wList.get(0).getProjectName();
        str_code = wList.get(0).getProductAcode();
        long_projectId = wList.get(0).getProjectId();
        long_deptId = wList.get(0).getDeptId();
        workhourID = wList.get(0).getWorkhourid();
        swipeCardPopBinding.tvSwipeProceedProject.setText(str_name + "(" + str_code + ")");
    }
    //  项目数据渲染 Spinner适配器
    public void setProject(){
        codeList.clear();
        adapter = new MyAdapter(projectnameList, MainActivity.this);
        swipeCardPopBinding.spProjectName.setAdapter(adapter);
        swipeCardPopBinding.spProjectName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "---项目名称---"+projectnameList.get(position).getProjectName()+
                        "--项目code---"+projectnameList.get(position).getProjectACode()+
                        "---项目 id---"+projectnameList.get(position).getProjectId()+
                        "---部门id--"+projectnameList.get(position).getDeptId()+
                        "--电气编码---"+projectnameList.get(position).getElectrialCode() );
                cleanProjectSelectInfo();
                str_name = projectnameList.get(position).getProjectName();
                str_code = projectnameList.get(position).getProjectACode();
                long_projectId = projectnameList.get(position).getProjectId();
                long_deptId = projectnameList.get(position).getDeptId();
                swipeCardPopBinding.tvSwipeSelectProject.setText(str_name+ "(" + str_code + ")");
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
     Boolean is_enter_out = false;  // 进入 出去状态
     public void addWorkHourCache (WorkHourCache workHourCache){
         is_enter_out = false;
         API.addWorkHourCache(workHourCache, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeCardPopBinding.btSwipeSubmit.setEnabled(true);
                        JSONObject j = JSONObject.parseObject(result);
                        long l = Long.parseLong(j.getString("code"));
                        if (l == 200){
                            is_enter_out = true;
                            ToastUtils.successShowLong(getApplicationContext(),"领料打卡成功！");
                            startAuto("领料打卡成功");
                            if (swipe_card_pop != null){
                                swipe_card_pop.dismiss();
                            }
                            closeDoorStatus();
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"领料打卡失败！");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
     }
     //  领料完成 提交
     public void updateCache(WorkHourCache workHourCache){
         is_enter_out = false;
        API.updateCache(workHourCache, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        afterWorkPopBinding.btAfterSubmit.setEnabled(true);
                        JSONObject j = JSONObject.parseObject(result);
                        long l = Long.parseLong(j.getString("code"));
                        String msg = j.getString("msg");
                        if (l == 200){
                            CacheDataManager.clearAllCache(MainActivity.this);  //清除缓存
                            ToastUtils.successShowLong(getApplicationContext(),msg);
                            startAuto("领料日志上报成功");
                            is_enter_out = true;
                            if (after_work_pop != null){
                                after_work_pop.dismiss();
                            }
                            closeDoorStatus();
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),msg);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
     }
    //  添加 缓存表
     public void AddWorkCacheManage(WorkHourCache workHourCache){
         API.addWorkHourCache(workHourCache, new IStringResponse() {
             @Override
             public void onSuccess(String result) {
                 MainActivity.this.runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         JSONObject j = JSONObject.parseObject(result);
                         long l = Long.parseLong(j.getString("code"));
                         if (l == 200){
                             ToastUtils.successShowLong(getApplicationContext(),"进门刷卡成功!");
                             mainBinding.etCardNumber.setText("");
//                             serialPortUtils.sendSerialPort("5501000000aa");
                             is_enter_out = true;
                         }else {
                             ToastUtils.warnShowLong(getApplicationContext(),"进门刷卡失败！请重新刷卡！");
                         }
                     }
                 });
             }
             @Override
             public void onFail(int statusCode) {}
         });
     }
     //  更新 缓存表
    public void updateWorkCache(WorkHourCache workHourCache){
         API.updateWorkCache(workHourCache, new IStringResponse() {
             @Override
             public void onSuccess(String result) {
                 MainActivity.this.runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         JSONObject j = JSONObject.parseObject(result);
                         long l = Long.parseLong(j.getString("code"));
                         if(l == 200){
                             ToastUtils.successShowLong(getApplicationContext(),"出门刷卡成功!");
//                             serialPortUtils.sendSerialPort("5501000000aa");
                             is_enter_out = true;
                             mainBinding.etCardNumber.setText("");
                         }else {
                             ToastUtils.warnShowLong(getApplicationContext(),"出门刷卡失败！请重新刷卡！");
                         }
                     }
                 });
             }
             @Override
             public void onFail(int statusCode) { }
         });
    }
     //  上报完成后 30秒 开门状态 关闭
     public void closeDoorStatus(){
         new Handler().postDelayed(new Runnable() {
             @Override
             public void run() {
                 is_enter_out = false;
             }
         },30 * 1000);
     }

     //  目录 弹窗
    PopupWindow menu_pop;
    MenuPopBinding menuPopBinding;
    public void showMenuPop(){
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(menu_pop == null){
                    menu_pop = new PopupWindow(getApplicationContext());
                    menuPopBinding = MenuPopBinding.inflate(getLayoutInflater());
                    View menuPop_view = menuPopBinding.getRoot();
                    menu_pop.setContentView(menuPop_view);
                    menu_pop.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                    menu_pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                    menu_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
                    menu_pop.setTouchable(true);
                    menu_pop.setFocusable(true);
                    menu_pop.setOutsideTouchable(true);
                    menu_pop.showAsDropDown(mainBinding.tvMenu, 10, -10);
                }else {
                    menu_pop.showAsDropDown(mainBinding.tvMenu, 10, -10);
                }
                setMenuPopListener();
            }
        });
    }
    //  目录 弹窗事件
    public void setMenuPopListener(){
        // 调节音量
        menuPopBinding.tvVolume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu_pop.dismiss();
                showVolumeBrightnessPop();
            }
        });
        // 绑定设备
        menuPopBinding.tvBindDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FactoryDeviceManagement device = new FactoryDeviceManagement();
                device.setSerialnumber(ANDROID_ID);
                addSerialNumber(device);

            }
        });
        // 开门 命令
        menuPopBinding.tvOpenDoor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: 点击开门测试");
                menu_pop.dismiss();
                popAddDevice();
            }
        });
        //   显示安卓ID
        menuPopBinding.tvAndroidId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu_pop.dismiss();
                ToastUtils.successShowLong(getApplicationContext(), " "+ ANDROID_ID+" ");
            }
        });
    }
    //
    PopupWindow password_pop;
    private int i;
    public void popAddDevice(){
        i = 0;
        setAlpha(0.5f);
        View password_view =  getLayoutInflater().inflate(R.layout.password_pop,null);
        EditText et_password = password_view.findViewById(R.id.et_password);
        ImageView iv_close = password_view.findViewById(R.id.iv_close);
        Button bt_password = password_view.findViewById(R.id.bt_password);
        int width = ScreenUtils.getWidth(getApplicationContext());
        password_pop = new PopupWindow
                (password_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        password_pop.setTouchable(true);
        password_pop.setFocusable(true);
        password_pop.setOutsideTouchable(true);
        bt_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeEditText(et_password);
                String str_password = et_password.getText().toString();
                if (str_password.equals("010203")){
                    serialPortUtils.sendSerialPort("5502000000aa");
                    password_pop.dismiss();
                    return;
                }
                i++;
                ToastUtils.warnShowLong(getApplicationContext(),"密码错误！,请重新输入!");
                if (i == 3){
                    ToastUtils.warnShowLong(getApplicationContext(),"请刷卡开门，请勿随意尝试!");
                    startAuto("请刷卡开门，请勿随意尝试!");
                    password_pop.dismiss();
                    closeEditText(et_password);
                }
            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                password_pop.dismiss();
                setAlpha(1f);

            }
        });
        password_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1f);
                closeEditText(et_password);
                closeEditText(mainBinding.etCardNumber);
            }
        });
        password_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,-100);
    }
    //  音量 控制 弹窗
    PopupWindow volume_bright_pop;
    public void showVolumeBrightnessPop(){
        View volume_bright_view = getLayoutInflater().inflate(R.layout.dialog_out_layout,null);
        int width = ScreenUtils.getWidth(getApplicationContext());
        volume_bright_pop = new PopupWindow
                (volume_bright_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        volume_bright_pop.setTouchable(true);
        volume_bright_pop.setFocusable(true);
        volume_bright_pop.setOutsideTouchable(true);
        volume_bright_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        volume_bright_pop.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    //  添加设备编号
    public void addSerialNumber (FactoryDeviceManagement deviceManagement){
        API.addSerialNumber(deviceManagement, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String msg = j.getString("msg");
                        long l = Long.parseLong(j.getString("code"));
                        if (l == 200){
                            ToastUtils.successShowLong(getApplicationContext(),"设备编号添加成功!");
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),msg);
                        }
                        if(menu_pop != null){
                            menu_pop.dismiss();
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                MainActivity.this.runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        ToastUtils.warnShowLong(getApplicationContext(), "添加设备编号网络异常！");
                    }
                });
            }
        });
    }
    //  清空下拉框项目数据
    public void cleanProjectSelectInfo(){
        str_name = null;
        str_code = null;
        long_projectId = null;
        long_deptId = null;
    }
    //  清空下拉框项目数据
    public void cleanProject(){
        if (projectnameList.size() > 0){
            projectnameList.clear();
            adapter = new MyAdapter(projectnameList, MainActivity.this);
            swipeCardPopBinding.spProjectName.setAdapter(adapter);
            str_name = null;
            str_code = null;
            long_projectId = null;
            long_deptId = null;
            swipeCardPopBinding.tvSwipeSelectProject.setText("");
        }
    }

    // 过期工单询问 dialog 弹窗
    private EasyDialog easyDialog;
    private long cancel_time = 0;
    private void showDialog(List<SysUser> sysUserList, List<WorkHourCache> oldCacheList) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EasyDialog.Builder builder = new EasyDialog.Builder(MainActivity.this)
                    .setContentView(R.layout.dialog_warm_tip2)
                    .addCustomAnimation(Gravity.CENTER, true)       //添加自定义动画
                    .setCancelable(false)            //设置对话框外部可取消
                    .setText(R.id.tv_title, "温馨提示")            //设置标题
                    .setText(R.id.tv_content, sysUserList.get(0).getNickName()+"_您有往期领料工单未处理，是否前往？")     //设置内容
                    //设置弹窗宽高
                    .setWidthAndHeight(EasyUtils.dp2px(MainActivity.this, 400), LinearLayout.LayoutParams.WRAP_CONTENT)
                    .setOnClickListener(R.id.tv_cancel, v1 -> {     //添加点击事件  取消
                        if ((System.currentTimeMillis() - cancel_time) > 2000){
                            ToastUtils.warnShowLong(MainActivity.this, "再按一次，取消上报！");
                            cancel_time = System.currentTimeMillis();
                        }else {
                            easyDialog.dismiss();
                        }
                    })
                    .setOnClickListener(R.id.tv_confirm, v2 -> {    //添加点击事件  确定
                        easyDialog.dismiss();
                        // true 代表是补卡，false 代表上报。showAfterWorkPop(sysUserList, oldCacheList, true);
                        if (oldCacheList.size() == 1){
                            showAfterWorkPop(sysUserList, oldCacheList, true);
                        }else {
                            ToastUtils.warnShowLong(MainActivity.this,"存在多条过期工单，请逐条处理！");
                            // 跳转到 异常工单页面
                            Intent intent = new Intent(MainActivity.this, AbnormalOrderActivity.class);
                            intent.putExtra("icCardNumber", sysUserList.get(0).getIcCard());
                            startActivity(intent);
                        }
                    })
                    .setOnCancelListener(dialog -> {  //添加外部取消监听
                    })
                    .setOnDismissListener(dialog -> {     //弹窗消失监听
                    });
                //创建弹窗
                easyDialog = builder.create();
                //显示弹窗
                easyDialog.show();
            }
        });
    }

    // 仓管 上报 弹窗
    private EasyDialog reportTipDialog;
    private void showReportTipDialog(List<SysUser> sysUserList) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EasyDialog.Builder builder = new EasyDialog.Builder(MainActivity.this)
                    .setContentView(R.layout.dialog_warm_tip)
                    .addCustomAnimation(Gravity.CENTER, true)  //添加自定义动画
                    .setCancelable(false)                               //设置对话框外部可取消
                    .setText(R.id.tv_title, "温馨提示")            //设置标题
                    .setText(R.id.tv_content, "请注意进出安全！")       //设置内容
                    .setText(R.id.tv_confirm, "去  开 门")
//                    .setText(R.id.tv_cancel, "取 消")
                    //设置弹窗宽高
                    .setWidthAndHeight(EasyUtils.dp2px(MainActivity.this, 400), LinearLayout.LayoutParams.WRAP_CONTENT)
//                    .setOnClickListener(R.id.tv_cancel, v1 -> {     //添加点击事件  取消
//                        reportTipDialog.dismiss();
//                        mainBinding.etCardNumber.setText("");
//                    })
                    .setOnClickListener(R.id.tv_confirm, v2 -> {      //添加点击事件  确定
                        reportTipDialog.dismiss();
                        WorkHourCache workHourCache_manage = new WorkHourCache();
                        workHourCache_manage.setProducedate(TimeUtils.getCurrentDate());
                        workHourCache_manage.setDeptid(sysUserList.get(0).getDeptId());
                        workHourCache_manage.setUserid(sysUserList.get(0).getUserId());
                        workHourCache_manage.setStarttime(TimeUtils.getCurrentDateTime());
                        workHourCache_manage.setClocktype("仓管");
                        workHourCache_manage.setStatus("0");
                        AddWorkCacheManage(workHourCache_manage);

                    })
                    .setOnCancelListener(dialog -> {  //添加外部取消监听
                    })
                    .setOnDismissListener(dialog -> {     //弹窗消失监听
                    });
                //创建弹窗
                reportTipDialog = builder.create();
                //显示弹窗
                reportTipDialog.show();
            }
        });
    }
    // 出库 提示弹窗
    private EasyDialog GoOutTipDialog;
    private void showGoOutTipDialog(TimeUtils.TimeInfo timeInfo, List<WorkHourCache> workHourCacheList) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EasyDialog.Builder builder = new EasyDialog.Builder(MainActivity.this)
                    .setContentView(R.layout.dialog_warm_tip)
                    .addCustomAnimation(Gravity.CENTER, true)       //添加自定义动画
                    .setCancelable(false)            //设置对话框外部可取消
                    .setText(R.id.tv_title, "入库停留时长")            //设置标题
                    .setTextColor(R.id.tv_content, R.color.royalblue)
                    .setText(R.id.tv_content, timeInfo.getTime() + " 小时")
                    .setText(R.id.tv_confirm, "去  开  门")
//                    .setText(R.id.tv_cancel, "取  消")
                    //设置弹窗宽高
                    .setWidthAndHeight(EasyUtils.dp2px(MainActivity.this, 400), LinearLayout.LayoutParams.WRAP_CONTENT)
//                    .setOnClickListener(R.id.tv_cancel, v1 -> {     //添加点击事件  取消
//                        GoOutTipDialog.dismiss();
//                    })
                    .setOnClickListener(R.id.tv_confirm, v2 -> {    //添加点击事件  确定
                        GoOutTipDialog.dismiss();
                        //  更新 缓存表数据
                        WorkHourCache workHourCache = new WorkHourCache();
                        workHourCache.setEndtime(timeInfo.getTimeStr());
                        workHourCache.setDuration(timeInfo.getTime()+"");
                        workHourCache.setStatus("1");
                        workHourCache.setWorkhourscacheid(workHourCacheList.get(0).getWorkhourscacheid());
                        updateWorkCache(workHourCache);
                    })
                    .setOnCancelListener(dialog -> {  //添加外部取消监听
                    })
                    .setOnDismissListener(dialog -> {     //弹窗消失监听
                    });
                //创建弹窗
                GoOutTipDialog = builder.create();
                //显示弹窗
                GoOutTipDialog.show();
            }
        });
    }

    //    弹窗 遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }
    //  设置 edittext有光标但不弹出软键盘
    public void closeInput(EditText editText){
        //4.0以上
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(editText, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    //  刷新 当前Activity
    private void reStartActivity() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    // 语音
    private void initTTS() {
//        MainActivity.this.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
                //实例化自带语音对象
                textToSpeech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int status) {
                        if (status == textToSpeech.SUCCESS) {
                            textToSpeech.setPitch(1.0f);//方法用来控制音调
                            textToSpeech.setSpeechRate(2.0f);//用来控制语速
                            //判断是否支持下面两种语言
                            int result1 = textToSpeech.setLanguage(Locale.US);
                            int result2 = textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE);
                            boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
                            boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);
                            Log.i("zhh_tts", "US支持否？--》" + a +
                                    "\nzh-CN支持否》--》" + b);
                        } else {
                            ToastUtils.warnShowLong(getApplicationContext(),"语音包数据丢失或不支持!!!");
                        }
                    }
                });
//            }
//        });
    }
    // 设置 语音
    private void startAuto(String data) {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        // 设置语速
        textToSpeech.setSpeechRate(1.0f);
        textToSpeech.speak(data,             //输入中文，若不支持的设备则不会读出来
                TextToSpeech.QUEUE_FLUSH, null,null);  // 有新任务时关闭语言，执行新的
    }

    //  activity 获取焦点时调用，解决语音返回桌面再次进入语音失效问题
    @Override
    protected void onResume() {
        super.onResume();
        initTTS();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (textToSpeech != null){
            textToSpeech.stop();      // 不管是否正在朗读TTS都被打断
            textToSpeech.shutdown(); // 关闭，释放资源
        }
    }

    @Override
    protected void onDestroy() {
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
//        Log.d(TAG, "onDestroy: ----销毁-----");
    }

    // 设置 按两次返回键 退出app
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                ToastUtils.warnShowLong(getApplicationContext(),"再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                // 退出 销毁
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    // 解决 内存不足时 杀死进程问题
    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Log.w(TAG,"=======> onTrimMemory, level=" + level + "=>" + printLevel(level));
        printLevel(level);
    }
    private String printLevel(int level) {
        String desc ;
        switch (level) {
            case TRIM_MEMORY_COMPLETE://80
                desc = "进程在LRU尾部,如果没有足够的内存, 将很快被杀死";
                CacheDataManager.clearAllCache(MainActivity.this);  //清除缓存
                break;
            case TRIM_MEMORY_MODERATE://60
                desc = "进程在LRU中部,如果系统进一步需要内存, 可能会被杀死";
                break;
            case TRIM_MEMORY_BACKGROUND://40
                desc = "进程在LRU头部,虽然本进程不会被高优杀死, 但系统已经开始准备杀死LRU列表中的其他进程";
                break;
            case TRIM_MEMORY_UI_HIDDEN://20
                desc = "界面不可见，建议释放UI资源";
                CacheDataManager.clearAllCache(MainActivity.this);
                break;
            case TRIM_MEMORY_RUNNING_CRITICAL://15
                desc = "虽然进程不会被高优杀死, 但系统已经开始准备杀死LRU列表中的其他进程，应该释放无用资源以防止性能下降";
                CacheDataManager.clearAllCache(MainActivity.this);  //清除缓存
                break;
            case TRIM_MEMORY_RUNNING_LOW://10
                desc = "虽然进程不会被高优杀死, 但系统已经开始准备杀死LRU列表中的其他进程，应该释放不必要的资源来提供系统性能";
                break;
            case TRIM_MEMORY_RUNNING_MODERATE://5
                desc = "系统已经进入了低内存的状态，进程正在运行但是不会被杀死";
                break;
            default:
                desc = "";
        }
        return desc;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    // 底部 透明导航栏
    public static void transparentNavBar(@NonNull final Activity activity) {
        transparentNavBar(activity.getWindow());
    }
    public static void transparentNavBar(@NonNull final Window window) {
        if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            window.setNavigationBarContrastEnforced(false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if ((window.getAttributes().flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0) {
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        }
        View decorView = window.getDecorView();
        int vis = decorView.getSystemUiVisibility();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(vis | option);
    }
    //  强制 关闭 软键盘
    public void closeEditText(EditText editText){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(),0);
    }

}